from django.core.cache import cache
from django.shortcuts import render


from rest_framework import viewsets, mixins, request
from rest_framework.decorators import api_view
from rest_framework.response import Response

from carts.models import CartModel
from goods.views import SKU
from user.models import User


@api_view(['POST'])
def cart(request):
    print('23333333333')
    id = cache.get(request.data['count'][1])
    user =User.objects.filter(id=id).first()
    sku = SKU.objects.filter(id=request.data['sku_id']).first()
    CartModel.objects.create(user=user,
                             sku=sku,
                             c_num=1,
                             is_select=1)
    res = {'count': 1}
    return Response(res)



class Carts(viewsets.GenericViewSet, mixins.ListModelMixin):
    queryset = CartModel.objects.all()

    def list(self, request, *args, **kwargs):
        id = cache.get(request.query_params['token'])
        carts = CartModel.objects.filter(user_id=id)
        allcart = []
        totalsku=0
        for cart in carts:

            a = cart
            dict1 = {}
            dict1['sku']={}
            dict1['sku']['name'] = cart.sku.name
            dict1['sku']['price'] = cart.sku.price
            dict1['selected'] = cart.is_select
            dict1['default_image_url'] = cart.sku.default_image_url
            dict1['amount'] = cart.c_num * int(cart.sku.price)
            totalsku += cart.c_num

            allcart.append(dict1)

        # name =
        # price =
        # selected =
        # default_image_url =
        # cart = {'sku': {'name': '', 'price': '' },
        #                        'selected': '',
        #                        'default_image_url': ''}
        res = {'totalsku': totalsku, 'code': 200, 'data': allcart}

        return Response(res)


